﻿using _8_21_Homework.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace _8_21_Homework.Controllers
{
    public class HomeController : Controller
    {
        List<Post> posts = Singleton.Instance.Posts;
        List<Post> searchPost = new List<Post>();
        public ActionResult SearchFor(string searching)
        {

            return RedirectToAction("Index",searchPost);
        }
        public ActionResult Index()
        {
            return View(posts);
        }
        [HttpGet]
        public ActionResult NewPost()
        {
            return View();
        }
        [HttpPost]
        public ActionResult NewPost(string title, string body)
        {
            Post p = new Post();
            p.Title = title;
            p.Body = body;
            p.DateCreated = DateTime.Now.ToString("g");
            posts.Insert(0, p);
            return RedirectToAction("Index");
        }

        public ActionResult PostDetail(int id)
        {
            var target = posts.Where(x => x.ID == id).FirstOrDefault();
            return View(target);
        }
        [HttpGet]
        public ActionResult EditPost(int id)
        {
            var target = posts.Where(x => x.ID == id).FirstOrDefault();
            return View(target);
        }
        [HttpPost]
        public ActionResult EditPost(string title, string body, int id)
        {
            var target = posts.Where(x => x.ID == id).FirstOrDefault();
            target.Title = title;
            target.Body = body;
            target.ID = id;
            return RedirectToAction("PostDetail/" + id);
        }
        [HttpGet]
        public ActionResult LeaveComment(int id)
        {
            var target = posts.Where(x => x.ID == id).FirstOrDefault();
            return View(target);
        }
        [HttpPost]
        public ActionResult LeaveComment(string userName, string commentText, int id)
        {
            Comment c = new Comment();
            c.Name = userName;
            c.Feedback = commentText;
            c.DateCreated = DateTime.Now.ToString("g");
            var target = posts.Where(x => x.ID == id).FirstOrDefault();
            if (target.comments == null)
            {
                target.comments = new List<Comment>();
            }
            target.comments.Add(c);
            return RedirectToAction("PostDetail/" + id);
        }
        public ActionResult Delete(int id)
        {
            var target = posts.Where(x => x.ID == id).FirstOrDefault();
            posts.Remove(target);

            return RedirectToAction("Index");
        }

        public ActionResult myErrorPage()
        {
            return View();
        }
    }
}